import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    Dimensions,
    ListView,
    TouchableOpacity,
    Platform,
    DeviceEventEmitter
} from 'react-native';
import InputLabelCompoment from "../compoment/InputLabelCompoment";
import LoginButCompoment from "../compoment/LoginButCompoment";
import {Toast,ModalIndicator,Overlay} from 'teaset';
import Utils from '../common/Utils'
import mqtt from '../common/mqtt'
const {height, width} = Dimensions.get('window');
const STORAGE_KEY_TOKEN = '@AsyncStorageDemo:key_token';
export default class LoginPage extends Component {
    componentDidMount() {
        this.msgListener = DeviceEventEmitter.addListener('OutIM',(listenerMsg) => {
            this.client.end();
        });
        this._loadInitialState().done();
    }
    componentWillUnmount() {
        this.msgListener&&this.msgListener.remove();
    }
    async _loadInitialState(){
        try{
            let value=await AsyncStorage.getItem(STORAGE_KEY_TOKEN);
            if(value!==null){
                this._appendMessage(value);
            }else{
                this._appendMessage('');
            }
        }catch(error){
            this._appendMessage('AsyncStorage错误'+error.message);
        }
    }
    _appendMessage=(message)=>{
        this.setState({
            token:this.state.token.concat(message)
        },()=>this.getInfo());
    };
    getInfo=()=>{
        if(this.state.token!=''){
            let params={
                "token":this.state.token,
            };
            ModalIndicator.show("正在请求数据......");
            fetch(Config.baseApi+'/user/loginByToken',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: Utils.getParamsString(params)
            })
                .then((response) => response.json())
                .then((responseJson) => {
                    ModalIndicator.hide();
                    if(responseJson.status===0){
                        mqttChat(responseJson.data.id);
                        AsyncStorage.removeItem(STORAGE_KEY_TOKEN);
                        AsyncStorage.setItem(STORAGE_KEY_TOKEN,responseJson.data.token);
                        Actions.reset('ChatPage');
                    }else if(responseJson.status===2){
                        Toast.message('请重新输入您的账号和密码');
                        Actions.reset('LoginPage')
                    }else{
                        Toast.message(responseJson.msg);
                    }
                })
                .catch((error) => {
                    ModalIndicator.hide();
                    Toast.message(error);
                });
        }
    };
    constructor(props) {
        super(props);
        this.state = {
            account:'',
            password:'',
            token:''
        }
    };
    login=()=>{
        let params={
            "userName":this.state.account,
            "password":this.state.password
        };
        ModalIndicator.show("正在请求数据......");
        fetch(Config.baseApi+'/user/login',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: Utils.getParamsString(params)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                ModalIndicator.hide();
                if(responseJson.status===0){
                    this.setState({
                        token:responseJson.data.token,
                        password:'',
                        account:''
                    },()=>{
                        mqttChat(responseJson.data.id);
                        AsyncStorage.removeItem(STORAGE_KEY_TOKEN);
                        AsyncStorage.setItem(STORAGE_KEY_TOKEN,responseJson.data.token);
                    });
                    Actions.reset('ChatPage')
                }else{
                    Toast.message(responseJson.msg);
                }
            })
            .catch((error) => {
                ModalIndicator.hide();
                Toast.message(error);
            });
    };

    render() {
        return (
            <View style={styles.container}>
                <View style={styles.titleView}>
                    <TouchableOpacity
                        onPress={()=>Actions.pop()}
                        style={styles.goBackView}>
                        <Image style={styles.titleLeftImg}/>
                    </TouchableOpacity>
                    <Text style={styles.titleMsg}>登录</Text>
                </View>
                <View style={{height:height/5,width:width}}/>
                <InputLabelCompoment
                    inputMsg={(msg)=>{
                        this.setState({
                            account:msg
                        })
                    }}
                    value={this.state.account}
                    secureTextEntry={false}
                    number={11}
                    text={'账号'}/>
                <View style={{height:20,width:width}}/>
                <InputLabelCompoment
                    inputMsg={(msg)=>{
                        this.setState({
                            password:msg
                        })
                    }}
                    value={this.state.password}
                    secureTextEntry={true}
                    number={11}
                    text={'密码'}/>
                <View style={{height:60,width:width}}/>
                <LoginButCompoment
                    login={()=>{
                        this.login()
                    }}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f0f0f0',
        alignItems:'center',
    },
    titleView:{
        height:iOS?64:44,
        paddingTop:iOS?20:0,
        alignItems:'center',
        justifyContent:'center',
        borderBottomWidth:0.5,
        borderColor:'#dbdbdb',
        backgroundColor:'#ffffff',
        width:width
    },
    goBackView:{
        position: 'absolute',
        left:15,
        height:iOS?64:44,
        paddingTop:iOS?20:0,
        justifyContent:'center',
        backgroundColor:'rgba(0,0,0,0)'
    },
    titleLeftImg:{
        height:20,
        width:20
    },
    titleMsg:{
        fontSize:17,
        color:'#000'
    },
});
